package com.newy.dao.sys;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.stereotype.Repository;

import com.newy.core.hibernate.HibernateDao;
import com.newy.domain.sys.Role;
import com.newy.domain.sys.RoleUser;
import com.newy.domain.sys.User;

/**
 * 用户与角色关联的dao类
 * @author linzongxue
 *
 */
@Repository
public class RoleUserDao extends HibernateDao<RoleUser, Long> {
	
	public List<Role> getRolesOfUser(Long userId){
		String hql = "select role from Role role, RoleUser roleUser where role.id=roleUser.roleId and roleUser.userId=?";
		return this.find(hql, userId);
	}
	
	public List<Role> getUnselectedRolesOfUser(Long userId){
		String hql = "from Role where id not in (select roleId from RoleUser where userId=?)";
		return this.find(hql, userId);
	}
	
	public List<User> getUsersOfRole(Long roleId){
		String hql = "select user from User user, RoleUser roleUser where user.id=roleUser.userId and roleUser.roleId=?";
		return this.find(hql, roleId);
	}

	public void clearRolesFromUser(Long userId){
		this.batchExecute("delete from RoleUser where userId=?", userId);
	}
	
	public void clearUsersFromRole(Long roleId){
		this.batchExecute("delete from RoleUser where roleId=?", roleId);
	}
	
	public void removeRolesFromUser(Long userId, Long[] roleIds){
		Map<String, Object> params = new HashMap<String, Object>(2);
		params.put("userId", userId);
		params.put("roleIds", roleIds);
		this.batchExecute("delete from RoleUser where userId=:userId and roleId in :roleIds", params);
	}
	
	public void removeUsersFromRole(Long roleId, Long[] userIds){
		Map<String, Object> params = new HashMap<String, Object>(2);
		params.put("roleId", roleId);
		params.put("userIds", userIds);
		this.batchExecute("delete from RoleUser where roleId=:roleId and userId in :userIds", params);
	}
}
